const Koa = require('koa');
const bodyParser  = require('koa-bodyparser')
const router = require('koa-router')()
const models = require('./models')
const moment = require('moment')
const app = new Koa();
app.use(async (ctx, next)=> {
  // 解决跨域和域检
  ctx.set('Access-Control-Allow-Origin', '*');
  ctx.set('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
  ctx.set('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
  if (ctx.method == 'OPTIONS') {
      ctx.body = 200; 
  } else {
      await next();
  }
});

router.post('/news_list', async ctx => {
  // 新闻列表

  let page = Number(ctx.request.body.page)
  let pageshow = Number(ctx.request.body.pageshow) || 5

  let news = await models.news.findAndCountAll({
    order: [
      ['created_at', 'DESC']
    ],
    include: {
      model: models.classify,
      attributes: ['cy_name'],
    },
    limit: pageshow,
    offset: (page - 1)*pageshow
  })

  return ctx.body = {
    code: 200,
    data: {
      list: news.rows.map(item => {
        let obj = JSON.parse(JSON.stringify(item))
        return {
          ...obj,
          created_at: moment(obj.created_at*1000).format('YYYY-MM-DD HH:mm:ss'),
        }
      }),
      count: news.count
    },
    msg: '操作成功'
  }
})

router.post('/classify_list', async ctx => {
  let page = Number(ctx.request.body.page)
  let pageshow = Number(ctx.request.body.pageshow) || 5
  let classify = await models.classify.findAndCountAll({
    limit: pageshow,
    offset: (page - 1)*pageshow
  })
  ctx.body = {
    code: 200,
    data: {
      list: classify.rows,
      count: classify.count
    },
    msg: '操作成功'
  }
})

app.use(bodyParser());
app.use(router.routes())

app.listen(3011)